<template>
  <div class="app-container" v-loading="isLoading">
    <el-form>
      <el-row>
        <el-col :span="3">
          <el-form-item>
            <el-button size="small" @click="$router.push('/order/custom')">返回上一页</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <div style="height: 36px;line-height: 40px"> 
              <span style="font-wight: blod;font-size: 24px">自动排产</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 原始第一页 -->
    <el-card v-if="!tableData.length" class="box-card-info">
      <div class="tips">自动排产是按订单“计划开工时间”自动筛选并综合计算：订单类型、方量权重、合同权重，客户权重等维度自动计算生成的生产任务于生产顺序</div>
      <div class="btn">
        <el-button @click="createTagHandle(0)" type="text">自动生成今日生产任务</el-button>
        <el-button @click="createTagHandle(1)" type="text">自动生成明日生产任务</el-button>
      </div>

      <div class="bottom" v-if="tipsFlag">
        <i class="el-icon-warning"></i>
        <span>暂无符合自动排产的订单</span>
      </div>
    </el-card>

    <el-card v-if="tableData.length" class="create-table">
      <div class="header-box">
        <div class="left-btn">
          <el-button @click="tabItemCheck(0)" :type="tabActiveIndex == 0 ? 'primary' : ''">今日生产任务</el-button>
          <el-button @click="tabItemCheck(1)" :type="tabActiveIndex == 1 ? 'primary' : ''">明日生产任务</el-button>
        </div>
        <div class="right-btn">
          <el-button @click="createTagHandle(0)" type="text">继续生成今日生产任务</el-button>
          <el-button @click="createTagHandle(1)" type="text">继续生成明日生产任务</el-button>
        </div>
      </div>

      <div class="table-box">
        <div class="table-header-wrap">
          <div class="left">
            <div>
              <i type="success" class="el-icon-success"></i>自动排产订单已生成
            </div>
            <div>
              {{ dayTxt }}待生产
              <span>{{ tableDataAutoList.length }}</span> 个订单，计划方量
              <span>{{ squareAmountTotal }}</span> 方
            </div>
          </div>
          <div class="right">
            <el-button @click="addHanle" type="primary" plain>新增</el-button>
            <el-button @click="generateTaskFn" type="primary" plain>加入生产任务</el-button>
          </div>
        </div>

        <el-table
          @selection-change="handleSelectionChange"
          :data="tableDataAutoList"
          style="width: 100%;margin-top: 15px;"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column align="center" prop="id" label="生产顺序" fixed="left"></el-table-column>
          <!-- 订单数据 -->
          <el-table-column align="center" prop="id" label="订单ID" fixed="left"></el-table-column>
          <el-table-column align="center" prop="orderType" label="订单来源" fixed="left"></el-table-column>
          <el-table-column align="center" prop="primaryDesignatorId" label="订单编号" fixed="left"></el-table-column>
          <el-table-column align="center" label="订单类型">
            <template slot-scope="scope">
              <span>{{ scope.orderType == 1 ? "来料加工" : "普通订单" }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="pay" label="是否预付款">
            <template slot-scope="scope">{{ scope.row.pay === 0 ? '否' : '是' }}</template>
          </el-table-column>
          <el-table-column label="订单状态">
            <template slot-scope="scope">
              <span v-if="scope.row.auditType == 0">拒绝</span>
              <span v-if="scope.row.auditType == 1">审核中</span>
              <span v-if="scope.row.auditType == 2">待生产</span>
              <span v-if="scope.row.auditType == 3">生产中</span>
              <span v-if="scope.row.auditType == 4">生产暂停</span>
              <span v-if="scope.row.auditType == 5">订单完工</span>
              <span v-if="scope.row.auditType == 6">订单过期</span>
              <span v-if="scope.row.auditType == 7">订单取消</span>
            </template>
          </el-table-column>

          <!-- 工程数据 -->
          <el-table-column prop="engineeringName" label="工程名称"></el-table-column>
          <el-table-column prop="construction_unit" label="施工单位"></el-table-column>
          <el-table-column prop="transport" label="运距"></el-table-column>
          <el-table-column prop="instructions" label="开工说明"></el-table-column>
          <el-table-column prop="address" label="施工地点"></el-table-column>

          <!-- 生产数据 -->
          <el-table-column prop="transVolume" label="累计生产方量"></el-table-column>

          <!-- 客户需求 -->
          <el-table-column prop="startTime" label="计划开工时间"></el-table-column>
          <el-table-column prop="plannedVolume" label="计划方量"></el-table-column>
          <el-table-column prop="positionName" label="部位名称">
            <template slot-scope="scope">{{ scope.row.positionName | positionFilter }}</template>
          </el-table-column>
          <el-table-column prop="pumpingId" label="泵送类型"></el-table-column>
          <el-table-column prop="slump" label="塌落度"></el-table-column>
          <el-table-column label="是否超方">
            <template slot-scope="scope">{{ scope.row.supersquare === 0 ? '否' : '是' }}</template>
          </el-table-column>
          <el-table-column prop="information" label="要求资料">
            <template slot-scope="scope">{{ scope.row.information === 0 ? '否' : '是' }}</template>
          </el-table-column>
          <el-table-column prop="ds" label="是否冬施">
            <template slot-scope="scope">{{ scope.row.ds === 0 ? '否' : '是' }}</template>
          </el-table-column>
          <el-table-column prop="deliveryTpye" label="配送方式">
            <template slot-scope="scope">{{ scope.row.deliveryTpye === 0 ? '需配送' : '自提' }}</template>
          </el-table-column>

          <!-- 物流数据 -->
          <el-table-column align="center" label="累计车次"></el-table-column>
          <el-table-column align="center" label="累计泵浆"></el-table-column>

          <!-- 标准配比数据 -->
          <el-table-column align="center" label="标准配合比"></el-table-column>

          <!-- 开盘配比数据 -->
          <el-table-column align="center" label="开盘配合比"></el-table-column>

          <!-- 时间戳 -->
          <el-table-column align="center" prop="startTime" label="时间戳"></el-table-column>

          <el-table-column align="center" label="操作列" fixed="right" width="100">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-top"
                @click="moveUp(scope.$index)"
                v-if="scope.$index !== 0"
              >上移</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-bottom"
                @click="moveDown(scope.$index)"
                v-if="scope.$index !== tableDataAutoList.length - 1"
              >下移</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="removeItem(scope.row,scope.$index)"
              >移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 新增 -->
    <addPop ref="addPop" :tabActiveIndex="tabActiveIndex" @updata="getAutoList" />
  </div>
</template>

<script>
import { autoSchedulingList, listOrders, orderMove, productionPlan, ordersExclude } from '@/api/service/orderCenter/automaticScheduling'
import addPop from './components/addPop.vue'
import utils from '@/utils/columnFilter.js';
export default {
  components: {
    addPop
  },
  data() {
    return {
      tabActiveIndex: 0,//0今日 1明日
      listParams: {
        pageNum: 1,
        pageSize: 10
      },
      isLoading: false,
      tipsFlag: false,
      tableData: [],//
      tableDataAutoList: [],//自动排产列表
      selectedRows: []
    };
  },
  filters: {
    positionFilter: utils.positionFilter
  },

  methods: {
    // 查询是否有符合自动排产的数据
    getList() {
      const time = this.tabActiveIndex == 0 ? utils.getTodayDate() : utils.getTomorrowDate();
      this.isLoading = true

      listOrders({
        startTime: time,//查询今天或者明天
        produceType: 0 // 查询待定的订单
      }).then(res => {
        // 查询待定的
        if (res.code == 200 && res.rows.length) {
          this.tipsFlag = false
          this.tableData = [...res.rows]
          this.getAutoList()
          return
        }
        this.tipsFlag = true
        this.tableData = []

      }).catch(error => {
        this.tableData = []
        this.tipsFlag = true
      }).finally(() => {
        // 无论成功或失败都会执行的代码
        this.isLoading = false
      });
    },
    // 查询已经加入自动排产的数据
    getAutoList() {
      // produceType 状态 0待定1加入自动排产2加入生产任务
      const time = this.tabActiveIndex == 0 ? utils.getTodayDate() : utils.getTomorrowDate();
      this.isLoading = true

      listOrders({
        startTime: time,//查询今天或者明天
        produceType: 1,// 查询排产订单
        auditType: 2 //2待生产
      }).then(res => {
        // 查询待定的
        if (res.code == 200 && res.rows.length) {
          this.tableDataAutoList = [...res.rows]
          return
        }
        this.tableDataAutoList = []
      }).catch(error => {
        this.tableDataAutoList = []
      }).finally(() => {
        // 无论成功或失败都会执行的代码
        this.isLoading = false
      });
    },

    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    addHanle() {
      this.$refs.addPop.showFilterDialog()
    },
    // tab切换点击查询
    tabItemCheck(index) {
      this.tabActiveIndex = index;
      this.getAutoList() //查询的是加入排产的数据
    },
    // (自动/继续)生成(今日/明日)任务  文字按钮点击
    createTagHandle(index) {
      this.tabActiveIndex = index;
      this.getList() //查询的是是否有符合排产的数据
    },
    // 上移动和下移动 belowOrderId 下订单id  upperOrderId 上订单id
    async movePositionApi(belowOrderId = '', upperOrderId = '') {
      // 创建表单对象
      const formData = new FormData();

      // 设置表单字段的值
      formData.append('belowOrderId', belowOrderId);
      formData.append('upperOrderId', upperOrderId);
      const res = await orderMove({
        belowOrderId,
        upperOrderId
      });
      return res; // 需要在函数末尾通过 return 返回一个 Promise 对象
    },
    // 上移动
    async moveUp(index) {
      const upItem = this.tableDataAutoList[index - 1];//上一行
      const cuItem = this.tableDataAutoList[index];//当前行
      await this.movePositionApi(cuItem.id, upItem.id);
    },
    // 下移动
    async moveDown(index) {
      const cuItem = this.tableDataAutoList[index];//当前行
      const nextItem = this.tableDataAutoList[index + 1];//下一行
      await this.movePositionApi(cuItem.id, nextItem.id);
    },
    // 加入生产任务
    generateTaskFn() {
      if (!this.selectedRows.length) return this.$message.error("您还没选择!");
      const ids = this.selectedRows.map(item => item.id);
      // 弹出确认操作
      this.$confirm(`确认加入生产计划吗?`, `已选${ids.length}个订单`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        productionPlan({
          orderIds: ids,
          time: utils.getTodayDateWithTime()
        }).then(res => {
          this.$message.success("加入生产任务成功!");
          this.getAutoList()
        });


      }).catch(() => {
        this.$message.info('取消加入生产计划');
      });
    },
    // 移除
    removeItem(row, index) {
      ordersExclude({
        orderId: row.id
      }).then(res => {
        this.$message.success("已移除!");
        this.getAutoList()
        // this.tableDataAutoList.splice(index, 1);
      });
    }
  },
  created() {
    this.userId = this.$route.query.id;
  },
  computed: {
    dayTxt() {
      return this.tabActiveIndex == 0 ? '今日' : '明日'
    },
    // 计划方量总和
    squareAmountTotal() {
      return this.tableDataAutoList.reduce((accumulator, currentValue) => {
        // 将当前值转换为数字类型，使用unary plus操作符或者parseInt方法
        const numericValue = +currentValue.squareAmount;
        // 如果无法转换为数字，则视为0
        return accumulator + (isNaN(numericValue) ? 0 : numericValue);
      }, 0);
    }
  },
};
</script>

<style lang="scss" scoped>
.hearder {
  display: flex;
  justify-content: flex-start;
  align-items: center;

  span {
    margin-left: 40px;
    font-weight: bold;
  }
}

@mixin flex-com {
  display: flex;
  justify-content: center;
  align-items: center;
}

.box-card-info {
  margin-top: 15px;
  padding: 15px;
  @include flex-com;

  .tips {
    font-size: 12px;
    color: #ccc;
  }

  .btn {
    @include flex-com;
    margin: 20px 0;

    .el-button {
      &:nth-of-type(2) {
        margin-left: 40px;
      }
    }

    .el-button--text {
      color: #409eff;
    }
  }

  .bottom {
    @include flex-com;
  }
}

.create-table {
  .header-box {
    @include flex-com;
    justify-content: space-between;
  }

  .table-box {
    margin-top: 30px;

    .table-header-wrap {
      @include flex-com;
      justify-content: space-between;

      .left {
        div:nth-of-type(2) {
          margin-left: 15px;
        }
      }
    }
  }
}
</style>
